﻿using System;
using InterfaceXAML.ExaPlanningService;
using Windows.UI;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;


// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace InterfaceXAML
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class LoginPage : Page
    {
        public LoginPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

        }

        private async void ConnexionClick(object sender, RoutedEventArgs args)
        {
            var login = "";
            var password = "";
            var reponse = false;

            Login.Document.GetText(TextGetOptions.NoHidden, out login);
            password = Password.Password;

            // Créer un nouveau proxy à chaque connexion, car ClientCredentials est en lecture seul une fois affecté.
            App.ExaPlanningServiceClient = new ExaPlanningServiceClient();

            App.ExaPlanningServiceClient.ClientCredentials.UserName.UserName = login;
            App.ExaPlanningServiceClient.ClientCredentials.UserName.Password = password;

            if(!string.IsNullOrEmpty(login) && !string.IsNullOrEmpty(password))
                try
                {
                    App.Utilisateur = await App.ExaPlanningServiceClient.LogInAsync();
                    reponse = true;
                }
                // Récupère les excéptions possibles du à un mauvais mot de passe ou mauvais login
                catch (Exception e)
                {
                    
                }

            if(!reponse)
            {
                var errorColor = App.ConvertToSolidColorBrush("#DD4B39");
                Login.BorderBrush = errorColor;
                Password.BorderBrush = errorColor;
            }
            else
            {
                Frame.Navigate(typeof(HomePage));
            }
        }


        private void BackButtonClick(object sender, RoutedEventArgs e)
        {
            Application.Current.Exit();
        }
    }
}
